<template>
  <Dropdown placement="bottomLeft" :overlayClassName="`${prefixCls}-dropdown-overlay`">
    <span :class="[prefixCls, `${prefixCls}--${theme}`]" class="flex">
      <img :class="`${prefixCls}__header`" :src="avatar" />
      <span :class="`${prefixCls}__info hidden md:block`">
        <span :class="`${prefixCls}__name  `" class="truncate">
          <span style="color: #a1a5b7">{{ loginUserName }}</span>
        </span>
      </span>
    </span>

    <template #overlay>
      <Menu @click="handleMenuClick">
        <MenuDivider v-if="getShowDoc" />
        <MenuItem
          v-if="getUseLockPage"
          key="lock"
          :text="l('LockScreen')"
          icon="ion:lock-closed-outline"
        />
        <MenuItem
          key="Password"
          :text="l('ChangePassword')"
          icon="ion:document-text-outline"
          v-if="getShowDoc"
        />
        <MenuItem
          key="LoginAttemp"
          :text="l('LoginAttempts')"
          icon="ion:document-text-outline"
          v-if="getShowDoc"
        />
        <MenuItem
          key="MySettings"
          :text="l('MySettings')"
          icon="ion:document-text-outline"
          v-if="getShowDoc"
        />
        <MenuItem key="backToMyAccount" text=" 返回原账号" v-if="isImpersonatedLogin" />
        <MenuItem key="logout" :text="l('LoginOut')" icon="ion:power-outline" />
      </Menu>
    </template>
  </Dropdown>
  <LockAction @register="register" />
</template>
<script lang="ts">
  // components
  import { Dropdown, Menu } from 'ant-design-vue';
  import { ProfileServiceProxy } from '/@/shared/service-proxies';

  import { defineComponent, computed, ref } from 'vue';

  import { DOC_URL } from '/@/settings/siteSetting';

  import { useUserStore } from '/@/shared/store/vbenModules/user';
  import { useHeaderSetting } from '/@/hooks/setting/useHeaderSetting';
  import { abpService, appSessionService } from '/@/shared/abp';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useModal } from '/@/components/Modal';
  import { ChangePasswordModal, LoginAttemptsModal, MySettingsModal } from './index';
  import { ModalHelper } from '/@/shared/helpers';
  import headerImg from '/@/assets/images/header.jpg';
  import { propTypes } from '/@/utils/propTypes';
  import { AppComponentBase } from '/@/shared/component-base';
  import { impersonationService } from '/@/shared/auth';
  import { openWindow } from '/@/utils';

  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';

  type MenuEvent =
    | 'logout'
    | 'doc'
    | 'lock'
    | 'Password'
    | 'LoginAttemp'
    | 'MySettings'
    | 'backToMyAccount';

  export default defineComponent({
    mixins: [AppComponentBase],
    name: 'UserDropdown',
    components: {
      Dropdown,
      Menu,
      MenuItem: createAsyncComponent(() => import('./DropMenuItem.vue')),
      MenuDivider: Menu.Divider,
      LockAction: createAsyncComponent(() => import('../lock/LockModal.vue')),
    },
    props: {
      theme: propTypes.oneOf(['dark', 'light']),
    },
    data() {
      return { avatar: '/assets/images/user.png', profileServiceProxy: new ProfileServiceProxy() };
    },
    created() {
      this.getProfilePicture();
    },
    mounted() {
      this.onUserAvatarChange();
    },
    methods: {
      onUserAvatarChange() {
        abp.event.on('userAvatarChange', (res) => {
          console.log('userAvatarChange watch');
          this.$nextTick(() => {
            this.avatar = res;
          });
        });
      },
      /**
       * 通过头像Id获取头像
       * @param profilePictureId 头像Id
       */
      getProfilePicture() {
        this.loading = true;
        let pid = abpService.loginInfo.user.profilePictureId;
        if (!pid) {
          this.avatar = '/assets/images/user.png';
        } else {
          this.profileServiceProxy
            .getProfilePictureById(pid)
            .finally(() => (this.loading = false))
            .then(async (result) => {
              if (result && result.profilePicture) {
                let profilePreviewImage = 'data:image/jpeg;base64,' + result.profilePicture;
                this.avatar = profilePreviewImage;
              }
            });
        }
      },
    },
    setup() {
      const { prefixCls } = useDesign('header-user-dropdown');
      const { t } = useI18n();
      const { getShowDoc, getUseLockPage } = useHeaderSetting();
      const userStore = useUserStore();
      const getUserInfo = computed(() => {
        const { realName = '', avatar, desc } = userStore.getUserInfo || {};
        return { realName, avatar: avatar || headerImg, desc };
      });

      const [register, { openModal }] = useModal();

      function handleLock() {
        openModal(true);
      }

      //  login out
      function handleLoginOut() {
        userStore.confirmLoginOut();
      }

      // open doc
      function openDoc() {
        openWindow(DOC_URL);
      }
      function changePassword() {
        ModalHelper.create(ChangePasswordModal, { width: 650 }).subscribe((result) => {
          if (result) {
            handleLoginOut();
          }
        });
      }
      function showLoginAttempts() {
        ModalHelper.create(LoginAttemptsModal).subscribe(() => {});
      }
      function changeMySettings() {
        ModalHelper.create(MySettingsModal, { width: 650 }).subscribe(() => {});
      }
      function backToMyAccount() {
        impersonationService.backToImpersonator();
      }

      function handleMenuClick(e: { key: MenuEvent }) {
        switch (e.key) {
          case 'logout':
            handleLoginOut();
            break;
          case 'doc':
            openDoc();
            break;
          case 'lock':
            handleLock();
            break;
          case 'Password':
            changePassword();
            break;
          case 'LoginAttemp':
            showLoginAttempts();
            break;
          case 'MySettings':
            changeMySettings();
            break;
          case 'backToMyAccount':
            backToMyAccount();
            break;
        }
      }

      return {
        prefixCls,
        t,
        getUserInfo,
        handleMenuClick,
        getShowDoc,
        register,
        getUseLockPage,
      };
    },
    computed: {
      isImpersonatedLogin() {
        if (typeof abp.session.impersonatorUserId === 'undefined') {
          return false;
        }
        return abp.session.impersonatorUserId > 0;
      },
      loginUserName() {
        return appSessionService.getShownLoginName();
      },
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-header-user-dropdown';

  .@{prefix-cls} {
    height: @header-height;
    padding: 0 0 0 10px;
    padding-right: 10px;
    overflow: hidden;
    font-size: 12px;
    cursor: pointer;
    align-items: center;

    img {
      width: 24px;
      height: 24px;
      margin-right: 12px;
    }

    &__header {
      border-radius: 50%;
    }

    &__name {
      font-size: 14px;
    }

    &--dark {
      &:hover {
        background-color: @header-dark-bg-hover-color;
      }
    }

    &--light {
      &:hover {
        background-color: @header-light-bg-hover-color;
      }

      .@{prefix-cls}__name {
        color: @text-color-base;
      }

      .@{prefix-cls}__desc {
        color: @header-light-desc-color;
      }
    }

    &-dropdown-overlay {
      .ant-dropdown-menu-item {
        min-width: 160px;
      }
    }
  }
</style>
